FORM ELEMENT EVENTS IN JAVASCRIPT
This note explains form element events in simple language.
You will learn:
- what the
submitevent is - why
preventDefault()is important - how to get form field values
- what the
changeevent does - what the
inputevent does - the difference between
changeandinput - what
focusandblurmean - what
document.activeElementis
Form events are very important because forms are everywhere in web development:
- login forms
- registration forms
- search fields
- settings pages
- contact forms
1. What are form element events?
Form element events are browser signals that happen when the user interacts with form elements.
Examples:
- submitting a form
- typing in an input
- changing a selected option
- focusing an input
- leaving an input
JavaScript can listen for these events and react.
Diagram 1. Basic idea
User interacts with form
|
v
browser creates event
|
v
JavaScript listens
|
v
handler function runs
Explanation
This is the basic pattern of all form events.
2. The submit event
A form is submitted in two common ways:
- when the user clicks a button with
type="submit" - when the user presses Enter while the cursor is inside a text field of the form
The submit event happens on the <form> element itself.
So the event listener should be added to the form, not to the submit button.
Example
const form = document.querySelector("form");
form.addEventListener("submit", event => {
console.log("Form submitted");
});
Diagram 2. How submit works
<form>
inputs
submit button
</form>
User clicks submit button
or presses Enter
|
v
submit event happens on form
|
v
form handler runs
Explanation
Even though the user may click the button, the actual submit event belongs to the form.
3. Default browser behavior on submit
Some browser events have built-in default behavior.
For forms, the default behavior of submit is usually:
- sending the form
- reloading the page
Most of the time, this is not what we want in JavaScript-based apps.
To stop the default browser behavior, use:
event.preventDefault()
Example
const form = document.querySelector("form");
form.addEventListener("submit", event => {
event.preventDefault();
console.log("Default form submission stopped");
});
Diagram 3. preventDefault()
submit event
|
v
browser wants to do default action
|
v
event.preventDefault()
|
v
default action is cancelled
Explanation
This is one of the most important things in form handling.
Without preventDefault(), the page may reload before your JavaScript finishes working.
4. Why submit is useful
The submit event is often used for:
- form validation
- checking empty fields
- comparing passwords
- building an object with user data
- sending data with JavaScript
Diagram 4. Typical submit workflow
User submits form
|
v
preventDefault()
|
v
read values
|
v
validate data
|
v
send or process data
5. Getting values from form fields
A form element has a useful property:
elements
This property contains references to form controls that have a name attribute.
That is why the name attribute is very important in forms.
Example HTML
<form class="login-form">
<input type="text" name="login" />
<input type="password" name="password" />
<button type="submit">Login</button>
</form>
Example JavaScript
const form = document.querySelector(".login-form");
form.addEventListener("submit", event => {
event.preventDefault();
const login = event.target.elements.login.value;
const password = event.target.elements.password.value;
console.log("Login:", login);
console.log("Password:", password);
});
Diagram 5. Accessing values through elements
event.target
|
v
form
event.target.elements
|
v
all named controls
event.target.elements.login.value
|
v
value of login field
Explanation
Here:
event.targetis the formelementsgives access to named controls.valuegives the current entered value
6. The change event
The change event happens after a form element has been changed.
But the exact behavior depends on the type of form element.
6.1 change on text fields and textarea
For text fields and textarea, change does not happen on every typed character.
It happens only:
- after the value changed
- and after the element loses focus
Example
const input = document.querySelector(".text-input");
input.addEventListener("change", event => {
console.log("Changed value:", event.target.value);
});
Diagram 6. change on text input
User types
|
v
no change event yet
User clicks outside input
|
v
input loses focus
|
v
change event happens
Explanation
This is why change is often not convenient for live typing reactions.
6.2 change on select, checkbox, and radio
For elements like:
select- checkbox
- radio button
the change event happens immediately when the value changes.
Example
const select = document.querySelector(".country-select");
select.addEventListener("change", event => {
console.log("Selected value:", event.target.value);
});
Diagram 7. change on select
User selects new option
|
v
value changes immediately
|
v
change event happens immediately
Explanation
For dropdowns, checkboxes, and radios, change is usually very natural and useful.
7. Useful properties of <select>
When working with a <select> element, three useful properties are:
valueselectedIndexoptions
Example
const select = document.querySelector(".country-select");
select.addEventListener("change", event => {
console.log("Value:", event.target.value);
console.log("Selected index:", event.target.selectedIndex);
console.log("Options:", event.target.options);
});
Diagram 8. <select> properties
<select>
option 0
option 1
option 2
</select>
value
|
v
selected option value
selectedIndex
|
v
position of selected option
options
|
v
collection of all options
Explanation
These properties are very useful when you need more than just the selected value.
8. The input event
The input event works only with:
- text inputs
textarea
It happens every time the value changes.
That means:
- when the user types
- when the user deletes text
It does not wait for focus loss.
Example
const input = document.querySelector(".text-input");
input.addEventListener("input", event => {
console.log("Current value:", event.target.value);
});
Diagram 9. input event
User types one character
|
v
input event happens
User types next character
|
v
input event happens again
User deletes character
|
v
input event happens again
Explanation
This is why input is the main event for real-time work with text fields.
9. input vs change
This is one of the most important comparisons.
input
- works on text fields and
textarea - happens every time the value changes
- does not need focus loss
change
- happens after the element value changed
- for text fields, waits until focus is lost
- for
select, checkbox, and radio, happens immediately
Diagram 10. input vs change
Text input:
input
|
v
every typed or deleted character
change
|
v
only after losing focus
Explanation
Easy rule:
input = live reaction
change = finished change
10. When to use input
Use input when you need:
- live text preview
- live validation
- search while typing
- character counting
- showing current value immediately
Example
const input = document.querySelector(".search-input");
const output = document.querySelector(".output");
input.addEventListener("input", event => {
output.textContent = event.target.value;
});
Diagram 11. Live typing
User types
|
v
input event
|
v
read current value
|
v
update page immediately
11. When to use change
Use change when you need:
- final value after editing a text input
- selected value in a dropdown
- checkbox or radio changes
Example
const checkbox = document.querySelector(".terms-checkbox");
checkbox.addEventListener("change", event => {
console.log("Checked:", event.target.checked);
});
Diagram 12. Checkbox change
User clicks checkbox
|
v
checked state changes
|
v
change event happens
12. The focus event
An element gets focus when:
- the user clicks it
- the user moves to it with the Tab key
- JavaScript calls
.focus()on it
The focus event happens when the element receives focus.
Example
const input = document.querySelector(".text-input");
input.addEventListener("focus", event => {
console.log("Input received focus");
});
Diagram 13. focus
User clicks input
or presses Tab to it
|
v
element becomes active
|
v
focus event happens
Explanation
focus is very useful when you want to start doing something as soon as the user enters the field.
13. The blur event
The blur event happens when an element loses focus.
This can happen when:
- the user clicks somewhere else
- the user tabs to another element
- JavaScript calls
.blur()
Example
const input = document.querySelector(".text-input");
input.addEventListener("blur", event => {
console.log("Input lost focus");
});
Diagram 14. blur
Input has focus
|
v
user clicks elsewhere
|
v
input loses focus
|
v
blur event happens
Explanation
blur is very useful for validation after the user finishes editing.
14. Why focus and blur are important
These two events are often used for:
focus
- loading autocomplete suggestions
- starting tracking
- highlighting the field
- showing tips
blur
- validating entered value
- hiding hints
- checking whether the user finished input
Diagram 15. Focus and blur workflow
focus
|
v
user starts work with field
blur
|
v
user finishes work with field
15. Programmatic focus and blur
JavaScript can also control focus directly.
Use:
element.focus()
element.blur()
Example
const input = document.querySelector(".text-input");
input.focus(); // give focus
input.blur(); // remove focus
Diagram 16. Programmatic control
JavaScript code
|
v
input.focus()
|
v
element gets focus
JavaScript code
|
v
input.blur()
|
v
element loses focus
16. document.activeElement
Only one element on the page can have focus at one time.
The currently focused element is available in:
document.activeElement
Example
console.log(document.activeElement);
Diagram 17. Active element
Page
|
v
many elements exist
|
v
only one is focused now
|
v
document.activeElement = that element
Explanation
This is useful when you need to know where the user is currently working.
17. Not all elements can receive focus
Most elements do not receive focus automatically.
For example, clicking a normal <div> usually does not make it focused, because it is not an interactive element.
Elements that usually can receive focus are:
inputtextareabuttonselect- link
Diagram 18. Focusable vs non-focusable
Usually focusable:
input
textarea
button
select
link
Usually not focusable by default:
div
span
p
Explanation
This is why focus and blur are most often used with interactive elements.
18. Full example with several form events
const form = document.querySelector(".login-form");
const loginInput = document.querySelector('input[name="login"]');
form.addEventListener("submit", event => {
event.preventDefault();
const login = event.target.elements.login.value;
const password = event.target.elements.password.value;
console.log("Submit");
console.log("Login:", login);
console.log("Password:", password);
});
loginInput.addEventListener("input", event => {
console.log("Input:", event.target.value);
});
loginInput.addEventListener("focus", () => {
console.log("Login input focused");
});
loginInput.addEventListener("blur", () => {
console.log("Login input blurred");
});
Diagram 19. Full flow
User focuses input
|
v
focus event
User types
|
v
input event many times
User leaves input
|
v
blur event
User submits form
|
v
submit event
|
v
preventDefault()
|
v
values are read
19. Common beginner mistakes
Mistake 1. Putting submit listener on the button instead of the form
The submit event belongs to the form.
Mistake 2. Forgetting preventDefault()
Without it, the browser may reload the page.
Mistake 3. Using change when you want live typing updates
For live text work, use input.
Mistake 4. Forgetting name attributes on form elements
Without name, access through form.elements becomes less useful.
Mistake 5. Thinking any clicked element gets focus
Only focusable elements receive focus normally.
Diagram 20. Common mistakes summary
submit -> listen on form
preventDefault() -> stop reload
input -> live typing
change -> later / finished change
name attribute -> important for form.elements
focus -> only on focusable elements
20. Easy memory rules
submit = form is being sent
preventDefault() = stop browser default action
input = every text change
change = final change
focus = element got focus
blur = element lost focus
document.activeElement = currently focused element
21. Quick summary
submithappens on the form.- Use
preventDefault()to stop the default browser action. form.elementsgives access to named form controls.changehappens after the value changes, and for text inputs usually after focus is lost.inputhappens on every text change.focushappens when an element gets focus.blurhappens when an element loses focus.document.activeElementstores the currently focused element.- Only one element can have focus at a time.
22. Final conclusion
If you understand these ideas:
submit
preventDefault()
elements
change
input
focus
blur
activeElement
then you already have a strong base for working with forms in JavaScript.
These events are used all the time in real projects:
- login forms
- search bars
- live validation
- dropdown selection
- settings pages
- user input tracking
23. Examples
Example 1. Submit validation
<div class="ex1-auth-example">
<div>
<form class="ex1-auth-form" autocomplete="off">
<input class="ex1-auth-input" type="text" name="login" placeholder="Login" />
<input class="ex1-auth-input" type="password" name="password" placeholder="Password" />
<button class="ex1-auth-btn" type="submit">Register</button>
</form>
<style>
.ex1-auth-form {
max-width: 600px;
margin: 0 auto;
text-align: center;
padding: 32px;
}
</style>
<script>
(function () {
const wrapper = document.currentScript.closest(".ex1-auth-example");
const registerForm = wrapper.querySelector(".ex1-auth-form");
registerForm.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault();
const form = event.target;
const login = form.elements.login.value;
const password = form.elements.password.value;
if (login === "" || password === "") {
console.log("Please fill in all the fields!");
return;
}
console.log(`Login: ${login}, Password: ${password}`);
form.reset();
}
})();
</script>
</div>
</div>
Conclusion: This example shows a form whose submission is handled with JavaScript. It demonstrates how to stop the default submit action with event.preventDefault(), read values from form fields, check whether the inputs are empty, and reset the form after successful submission.
Example 2. Select change
Selected option text: none
Selected option value: none
<div class="ex2-pizza-example">
<div>
<p>
Selected option text: <span class="ex2-text-output">none</span>
</p>
<p>
Selected option value: <span class="ex2-value-output">none</span>
</p>
<select class="ex2-pizza-select">
<option value="four_meats">Four Meats</option>
<option value="royal_cheese">Royal Cheese</option>
<option value="vegetarian">Vegetarian</option>
<option value="smoked_salmon">Smoked Salmon</option>
</select>
<style>
.ex2-pizza-select {
padding: 4px;
}
</style>
<script>
(function () {
const wrapper = document.currentScript.closest(".ex2-pizza-example");
const select = wrapper.querySelector(".ex2-pizza-select");
const textOutput = wrapper.querySelector(".ex2-text-output");
const valueOutput = wrapper.querySelector(".ex2-value-output");
select.addEventListener("change", setOutput);
function setOutput(event) {
const selectedOptionValue = event.currentTarget.value;
const selectedOptionIndex = event.currentTarget.selectedIndex;
const selectedOptionText =
event.currentTarget.options[selectedOptionIndex].text;
textOutput.textContent = selectedOptionText;
valueOutput.textContent = selectedOptionValue;
}
})();
</script>
</div>
</div>
Conclusion: This example shows how JavaScript can react to a change in a select element. It demonstrates how to read both the selected value and the visible option text, and then display them on the page.
Example 3. Live text input
Text field value:
<div class="ex3-text-example">
<div>
<input type="text" class="ex3-text-input" />
<p>Text field value: <span class="ex3-output"></span></p>
<style>
.ex3-text-example {
line-height: 1.5;
font-family: sans-serif;
color: #f1f1f1;
}
.ex3-text-example p {
overflow-wrap: anywhere;
}
.ex3-text-example .ex3-text-input {
width: 100%;
max-width: 320px;
padding: 8px;
font: inherit;
}
</style>
<script>
(function () {
const wrapper = document.currentScript.closest(".ex3-text-example");
const textInput = wrapper.querySelector(".ex3-text-input");
const output = wrapper.querySelector(".ex3-output");
textInput.addEventListener("input", function (event) {
output.textContent = event.currentTarget.value;
});
})();
</script>
</div>
</div>
Conclusion: This example shows how JavaScript can react to typing in a text field. It demonstrates the input event and shows how the current value of the input can be displayed live on the page.
Example 4. Focus and blur controls
<div class="ex4-focus-example">
<div>
<div class="ex4-controls">
<button type="button" data-action="set">Set focus to input</button>
<button type="button" data-action="remove">Remove focus from input</button>
</div>
<input type="text" class="ex4-text-input" />
<style>
.ex4-focus-example .ex4-controls {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 12px;
}
.ex4-focus-example .ex4-text-input {
width: 100%;
max-width: 320px;
padding: 8px;
font: inherit;
}
.ex4-focus-example button {
display: inline-flex;
padding: 4px 8px;
}
</style>
<script>
(function () {
const wrapper = document.currentScript.closest(".ex4-focus-example");
const textInput = wrapper.querySelector(".ex4-text-input");
const setFocusBtn = wrapper.querySelector('[data-action="set"]');
const removeFocusBtn = wrapper.querySelector('[data-action="remove"]');
setFocusBtn.addEventListener("click", function () {
textInput.focus();
});
removeFocusBtn.addEventListener("click", function () {
textInput.blur();
});
textInput.addEventListener("focus", function () {
textInput.value = "This input has focus";
});
textInput.addEventListener("blur", function () {
textInput.value = "";
});
})();
</script>
</div>
</div>
Conclusion: This example shows how JavaScript can control focus on an input element. It demonstrates focus(), blur(), and the focus and blur events to change the input value when the field becomes active or inactive.